<?php
function addslashes_deep($value){if (empty($value)){return $value;}else{return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);}}
function unregister_globals(){if (!ini_get('register_globals')){return false;}foreach (func_get_args() as $name){foreach ($GLOBALS[$name] as $key=>$value){if (isset($GLOBALS[$key])){ unset($GLOBALS[$key]);}}}}

//取消HTML代码
function htmlFilter($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = shtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
			str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}

//过滤非法字符
function strFilter($str){
	//TODO: 过滤非法字符
	return $str;
}

//数字检测
function numFilter($num){
	//TODO: 数字参数的特殊处理
	return intval($num);
}

//是否为合法的用户名
function isValidName($str){
	$reg="/^[\w\x80-\xff]+$/i";
	if(preg_match($reg,$str)){
		return true;
	}
	return false;
}

//是否为合法的邮箱
function isValidEmail($str){
	$reg="/[a-z0-9]([a-z0-9]*[-_\.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?/i";
	if(preg_match($reg,$str)){
		return true;
	}
	return false;
}

//encrypt
function encrypt($username,$userpass){
	$str=$username.$userpass;
	return empty($str)?'':md5(strtolower($str));
}

//截取字符串
function cutStr($str,$len,$add=true){
    //Get the display width of the string.
    $i =0;
    $j =0;
    $str_width = 0;
    do{
            if(ord($str[$i]) > 224){
                    $str_width += 2;
                    $i += 3;
                }
            else if(ord($str[$i] > 192)){
                    $str_width += 2;
                    $i += 2;
                }
            else{
                    $str_width++;
                    $i++;
                }
        }while($i<strlen($str));
    //IF the display width is shorter than you want ,return the string.
    if($str_width < $len)
        {
            return $str;
        }
    else{
            $i = 0;
            $j = 0;
            $newword = '';
            do{
                    //If the character is a Chinese
                    if(ord($str[$i]) > 224){
                            $newword .= $str[$i].$str[$i+1].$str[$i+2];
                            $i = $i +3;
                            $j =$j + 2;
                        }
                    //If the character is a symble
                    else if(ord($str[$i] > 192)){
                            $newword .= $str[$i].$str[$i+1];
                            $i = $i + 2;
                            $j = $j + 2;
                        }
                    //If the character is a alpha
                    else{
                            $newword .= $str[$i];
                            $i++;
                            $j++;
                        }
                }while($j<$len);
            if($add){
                    return $newword.'...';
                }
            else
                return $newword;
        }

}

//int->date 显示时间(人性化时间)
/*
	getDateStr(时间戳, 只显示日期, 使用人性化时间)
*/
function getDateStr($dateint, $dateonly=false, $usehmt='-1'){
	global $cache_settings;
	$time_offset=$cache_settings['timeoffset'];
	$usehuman=($usehmt=='0'||empty($usehmt))?false:$cache_settings['humantime']=='1';
	$datedif=intval(time()-$dateint);
	if($usehuman){
		if($datedif<0){
			$usehuman=false;
		}elseif($datedif<60){
			$datedif=$datedif==0?1:$datedif;
			return "{$datedif}秒前";
		}elseif($datedif<3600){
			$datedif=intval($datedif/60);
			return "{$datedif}分钟前";
		}elseif($datedif<3600*24){
			$datedif=intval($datedif/3600);
			return "{$datedif}小时前";
		}elseif($datedif<3600*24*2){
			return "昨天".gmdate('H:i',($dateint-3600*24)+$time_offset*3600);
		}else{
			$usehuman=false;
		}
	}
	if(!$usehuman){
		$df=$dateonly ? $cache_settings['timeformat']  : $cache_settings['timeformat']." H:i";
		$df = str_replace(array('yyyy','mm','dd'), array('Y','m','d'), $df);
		return gmdate($df,$dateint+$time_offset*3600);
	}
}


function getCacheFilePath($filename){
	return INC_P."/../cache/{$filename}"; 
}

function getAdminStr($admins){
	$str='';
	foreach(explode("|",$admins) as $value){
		if($value==''){
			continue;
		}
		$str.="<a href='user.php?username={$value}' target='_blank'>{$value}</a>&nbsp; ";
	}
	if(empty($str)){
		$str='空缺中';
	}
	return $str;
}


//获取权限
function getPopedom($k){
	global $lg;
	global $cache_groups;
	$p=$cache_groups[$lg['groupid']]['popedom'];
	$ps=explode("|",$p);
	return ($k==17?$ps[$k]:intval($ps[$k]));
}

//获取积分
function getAllCredits($exp, $row){
	$exp=str_replace(	array('postsnum', 'credits1', 'credits2', 'credits3', 'credits4', 'credits5', 'credits6', 'credits7', 'credits8' ), 
								array($row['postsnum'], $row['credits1'], $row['credits2'], $row['credits3'], $row['credits4'], $row['credits5'], $row['credits6'], $row['credits7'], $row['credits8']), 
								$exp
							);
		try{
			eval("\$r={$exp};");
		}catch(Exception $e){
			exit("总积分公式错误，无法计算结果。");
		}
		return $r;
}


//毫秒时间
function getmicrotime(){
	list($usec, $sec) = explode(" ",microtime());
	return ((float)$usec + (float)$sec);
}

//返回模板路径
function getTemplatePath($filename){
	global $_SYS;
	$tpl="{$_SYS['TP']}/{$filename}";
	if(!file_exists($tpl)){
		$tpl="template/6kbbs/{$filename}";
	}
	return $tpl;
}

//是否管理员
function isAdmin(){
	global $lg;
	return ($lg['groupid']==GROUP_ADMIN && $lg['isadmin']==1);
}

//是否版块管理员
function isForumAdmin($fid){
	global $lg;
	global $cache_forums;
	if($lg['groupid']==GROUP_SUPERADMIN || $lg['groupid']==GROUP_ADMIN){
		return true;
	}
	if($lg['groupid']==GROUP_FORUMADMIN && stristr($cache_forums[$fid]['admins'].$cache_forums[$fid]['padmins'],"|{$lg['username']}|")){
		return true;
	}
	return false;
}

//_header_
function _header_($string, $isreplace = true, $code = 0) {
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if(empty($code) || PHP_VERSION < '4.3' ) {
		@header($string, $isreplace);
	} else {
		@header($string, $isreplace, $code);
	}
	if(preg_match('/^\s*location:/is', $string)) {
		exit();
	}
}

//加减积分
function updateCredits($uid, $actionvar){
	global $cache_credits;
	global $db;
	foreach($cache_credits as  $code=>$actionarr){
		$value = $actionarr[$actionvar];
		$user[$code]="$code+({$value})";
		$user["NOQUOTE_".$code]=true;
	}
	$db->row_update("users",$user,"id={$uid}");
}

//消息通知
function printMsg($code){
	ob_clean();
	$msg_code = $code;
	require_once('msg.php');
	exit();
}

//获取客户端IP

function getIP() {
	$cip = '';
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$cip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$cip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$cip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$cip = $_SERVER['REMOTE_ADDR'];
	}
	return is_ip($cip)?$cip:'127.0.0.1';
}

function is_ip($str){
	return ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$str); 
}


function setCookies($name, $value, $keep=0, $httponly=false) {
	global $_SYS;
	$path = $httponly && PHP_VERSION < '5.2.0' ? $_SYS['cookiepath']."; HttpOnly" : $_SYS['cookiepath'];
	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	$keep = $keep?(time()+$keep):0;
	if(PHP_VERSION < '5.2.0'){
		setcookie($_SYS['cookiepre'].$name, $value, $keep, $path, $_SYS['cookiedomain'], $secure);
	} else {
		setcookie($_SYS['cookiepre'].$name, $value, $keep, $path, $_SYS['cookiedomain'], $secure, $httponly);
	}
}

function getCookies($name){
	global $_SYS;
	return $_COOKIE[$_SYS['cookiepre'].$name];
}


//生成广告
function getAd($target){
	global $cache_ads;
	$curtime = time();
	$result=array();
	foreach($cache_ads as $adtype=>$ads){
		$res='';
		$arr=array();
		foreach($ads as $ad){
			if($ad['starttime']>$curtime || ($ad['stoptime']<$curtime && $ad['stoptime']>0)){
				continue;
			}
			if(stristr(",{$ad['targets']},", ",{$target},") || $ad['targets']=='all'){
				array_push($arr, $ad);
			}
		}
		if(empty($arr)){
			$res='';
		}else{
			switch(intval($adtype)){
				case 1:
					$res='<div class="ad_1">'.ad2html($arr, 'random').'</div>';
				break;
				case 2:
					$res= '<div class="ad_2">'.ad2html($arr, 'random').'</div>';
				break;
				case 3:
					$res= '<div class="ad_3">'.ad2html($arr, 'list').'</div>';
				break;
				case 4:
					//帖间广告，返回广告数组
					$res= $arr;
				break;
			}
		}
		$result[$adtype]=$res;
	}
	return $result;
}

function ad2html($arr, $t='list'){
	$arrnum = count($arr);
	$str='';
	if($t=='list'){
		$tdnum=$arrnum>3?4:$arrnum;
		$str.='<table>';
		$index=0;
		for($i=0; $i<$arrnum/4; $i++){
			$str.="<tr>";
				for($j=0;$j<$tdnum;$j++){
					$str.="<td width=".number_format(100/$tdnum,2)."%>{$arr[$index]['code']}</td>";
					$index++;
				}
			$str.="</tr>";
		}
		$str.='</table>';
	}elseif($t=='random'){
		$str=$arr[mt_rand(0,$arrnum-1)]['code'];
	}
	return $str;
}

function getStar($num=1){
	$s="";
	$n_4 = intval($num / 4); $num = $num % 4; $n_2 = intval($num / 2); $n_1 = intval($num % 2);
	for($n=0; $n<$n_4; $n++){
		$s.="<i class=star_4></i>";
	}	
	for($n=0; $n<$n_2; $n++){
		$s.="<i class=star_2></i>";
	}	
	for($n=0; $n<$n_1; $n++){
		$s.="<i class=star_1></i>";
	}	
	return $s;
}

//获取访问目录路径	$predir = -1 ： 返回上级目录
function getUrlPath($predir=0){
	$pathdir=pathinfo($_SERVER['SCRIPT_NAME']);
	$pathdir=$pathdir['dirname'];
	$pathdir=$pathdir=='\\'?'':$pathdir;
	if($predir<0 && $pathdir!=''){
		$s=explode('/', $pathdir);
		$pathdir='';
		for($n=0;$n<count($s)+$predir; $n++){
			if(empty($s[$n]))continue;
			$pathdir.='/'.$s[$n];
		}
	}
	$url="http://{$_SERVER['HTTP_HOST']}{$pathdir}";
	return $url;
}

//帖子图标
function getTopicIcon($topic){
	if($topic['isalltop']){return array('alltop','总置顶帖');}
	if($topic['istop']){return array('top','置顶帖');}
	if($topic['isgood']){return array('good','精华帖');}
	if($topic['islock']){return array('lock','锁定的帖子');}
	if($topic['topictype']==2){return array('reward','悬赏');}
	if($topic['topictype']==1){return array('vote','投票');}
	return array('normal','');
}

function genHighLighStr($highlight, $title){
	$hls=explode(",",$highlight);
	if(!empty($hls[0])){$title="<span style='color:{$hls[0]}'>{$title}</span>";}
	if(!empty($hls[1])){$title="<b>{$title}</b>";}
	if(!empty($hls[2])){$title="<i>{$title}</i>";}
	if(!empty($hls[3])){$title="<u>{$title}</u>";}
	return $title;
}

//是否登录
function isLogin(){
	global $lg;
	return $lg['userid']>0;
}

//底部
function footer($f=true){
	global $timer_begin;
	global $db;
	global $cache_settings;
	$times=$db->query_count();
	$time_now=getDateStr(time(),false,false);
	$timer_end=getmicrotime();
	$timer_run = round($timer_end-$timer_begin,6);
	if($f){
		require_once getTemplatePath('footer.htm');
	}
	ob_end_flush();
	exit;
}

function _clear_($output){
	$output = str_replace(array('<!--<!--<!---->','<!---->-->','<!--<!---->',"<!---->\r\n",'<!---->','<!-- -->',"\t\t\t"),'',$output);
	$output = preg_replace("/\n\s*\r/is", "", $output);
	return $output;
}

function genUrl($url){
	if(empty($url))return "";
	global $cache_settings;
	$urlrewrite = intval($cache_settings['urlrewrite']);
	$http_host=($_SERVER["HTTPS"]=='on'?'https':'http').'://'.$_SERVER['HTTP_HOST'];
	switch($urlrewrite){
		case 0:
			return $url;
		break;
		case 1:	//伪静态的方式1,程序实现
			$_p = preg_replace("/\/(.[^\/]*).php/is", "", $_SERVER['PHP_SELF']);
			$url = str_replace("index.php", "{$_p}/?index.html", $url);
			$url = preg_replace("/forum.php\?fid=(\d{1,})(&page=(.*))*/is", "{$_p}/?forum-\\1-\\3.html", $url);
			$url = preg_replace("/view.php\?tid=(\d{1,})(&page=(.*))*/is", "{$_p}/?view-\\1-\\3.html", $url);
			$url = preg_replace("/user.php\?uid=(\d{1,})(&page=(.*))*/is", "{$_p}/?user-\\1-\\3.html", $url);
			$url = str_replace("-.html", ".html", $url);
			return $http_host.$url;
		break;
		case 2:	//伪静态的方式2,urlrewrite rule
			$_p = preg_replace("/\/(.[^\/]*).php/is", "", $_SERVER['PHP_SELF']);
			$url = str_replace("index.php", "{$_p}/index.html", $url);
			$url = preg_replace("/forum.php\?fid=(\d{1,})(&page=(.*))*/is", "{$_p}/forum-\\1-\\3.html", $url);
			$url = preg_replace("/view.php\?tid=(\d{1,})(&page=(.*))*/is", "{$_p}/view-\\1-\\3.html", $url);
			$url = preg_replace("/user.php\?uid=(\d{1,})(&page=(.*))*/is", "{$_p}/user-\\1-\\3.html", $url);
			$url = str_replace("-.html", ".html", $url);
			return $http_host.$url;
		break;
	}
	return $url;
}

?>